package com.sgy.netty;

import com.sgy.netty.codec.MessageCodec;
import com.sgy.netty.codec.MessageDecoder;
import com.sgy.netty.codec.MessageEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.nio.channels.SocketChannel;

public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        // 创建bossGroup线程组处理连接事件
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);

        // 创建workGroup线程组处理读写事件
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        // 创建服务端启动助手
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 设置bossGroup和workerGroup
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)  // 设置通道实现为nio
                .option(ChannelOption.SO_BACKLOG, 128)  // 设置参数
                .childOption(ChannelOption.SO_KEEPALIVE, true)  // 设置通道活跃状态
                .childHandler(new ChannelInitializer<Channel>() {  // 创建通道初始化对象
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        // 添加自定义解码器
                        // channel.pipeline().addLast("messageDecoder", new MessageDecoder());

                        // 添加定义编码器
                        // channel.pipeline().addLast("messageEncoder", new MessageEncoder());

                        // 添加编解码器
                        channel.pipeline().addLast(new MessageCodec());

                        // 向pipeline中添加自定义业务处理handler
                        channel.pipeline().addLast(new NettyServerHandler());
                    }
                });

        // 启动服务端并绑定端口，同时将异步改为同步
        // ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();  // 同步处理
        ChannelFuture channelFuture = serverBootstrap.bind(9999);  // 异步处理
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    System.out.println("端口绑定成功...");
                } else {
                    System.out.println("端口绑定失败...");
                }
            }
        });
        System.out.println("服务端启动成功...");

        // 关闭通道（不是真正意义的关闭，而是监听通道关闭状态）和关闭连接池
        channelFuture.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
